var dbutil = require("../database/dbutil");
var mongoose = require('mongoose');
var User = mongoose.model("User");


exports.userList = function (req, res) {

    console.log("diagnostic getting to game.js");


    dbutil.lookup(function (userMap) {


        console.log(userMap);
        res.render(

            "lookupPlayer", {
                usernames: userMap,
                title: "player list"

            });
    });

};

exports.adminPage = function (req, res) {
    dbutil.lookup(function (userMap) {
        res.render(
            "admin",{
            usernames: userMap,
            title: "player list"

        });
    });

};


exports.lookonline = function (req, res) {
    var username = req.body.username,
        password = req.body.password;


    console.log("diagnostic getting to game.js look online");

    dbutil.online(username, password, function (useronline) {

            if (useronline.username === username && useronline.password === password) {
                console.log("successful login from game.lookonline amigo");

                if (useronline.isAdmin) {
                    exports.adminPage(req, res);

                }


                else {
                    res.render("test1", {message: "successful login"});
                }
            }
            else {
                console.log("user could not log in, wrong username or password");
                console.log(useronline);
                res.render("test1", {message: "could not log in"});
            }

        }
    );
};


exports.createUser = function (req, res) {
    var username = req.body.username,
        password = req.body.password;

    dbutil.saveUser(username, password, function (done, message) {
        if (done) {
            res.render("test1", {message: message});
        } else {
            res.render("test1", {message: message});
        }
    });

};



exports.remove = function (req, res) {
    var deleteUsers = req.body.username;
    console.log(deleteUsers);
    deleteUsers.forEach(function (user) {
        dbutil.removeUser(user);
    });
    exports.adminPage(req, res);

};

exports.change = function (req, res) {

    var originalName = req.body.originalUsername.replace(/"/g, "");
    var newName = req.body.newUsername.replace(/"/g, "");

    console.log("updating username " + originalName + " to " + newName);

    dbutil.updateUser(newName, originalName, function (done, message) {
        if (done) {
            exports.adminPage(req, res);
            //res.render("admin", {message: message});
        } else {
            res.render("test1", {message: message});
        }
    });
};